<template>
  <div :id="props.id" class="main">

  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus';
import { ta } from 'element-plus/es/locales.mjs';
import { computed, onMounted, reactive, ref, watch, toRaw } from 'vue';

// 请求模式（天/周/月/年）
let mode = ref("day")
// 图信息（包含title，Unit)
let data = ref(null)
let ifPredict = ref(false)
let hasChart = ref(false)
var myChart

let props = defineProps({
  id: {
    type: String,
    default: "main"
  },
  data: {
    type: Object,
    default: null
  },
  ifPredict: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    default: "day"
  }
})

watch(props, (newVal, oldVal) => {
  data.value = newVal.data
  ifPredict.value = newVal.ifPredict
  mode.value = newVal.mode
  clearChart()
  initChart()
})

// 所有图表具体数据(所有表的集合)
let tableData = computed(() => {
  if (data.value == null || data.value.data == null) return null
  return data.value.data
})

let series = computed(() => {
  return tableData.value.flatMap((item) => {
    const actuallData = item.data
    return [
      {
        name: `${item.name}`,
        type: 'line',
        data: actuallData,
        itemStyle: { color: item.color },
        symbol: 'none',
        tooltip: {
          trigger: 'axis'
        },
        // 强调样式，当鼠标悬浮到线上时，会突出显示对应的点
        emphasis: {
          focus: 'series'
        }
      }
    ];
  })
})


const clearChart = () => {
  if (hasChart.value == true) {
    myChart.clear()
    hasChart.value = false
  }
}

function getDateInterval(arr) {
  let max = arr[0];
  let min = arr[0];
  arr.forEach((item, index) => {
    if (Date.parse(item) > Date.parse(max)) {
      max = item;
    }
    if (Date.parse(item) < Date.parse(min)) {
      min = item;
    }
  });
  return {
    endDate: max,
    beginDate: min,
  };
}

const initChart = () => {
  if (hasChart.value == false) {
    myChart = echarts.init(document.getElementById(props.id));
    hasChart.value = true
  }
  let dateArr = data.value.data.flatMap((item) => {
    return item.data.map((item2) => item2[0])
  })
  let { beginDate, endDate } = getDateInterval(dateArr)
  let option = {
    title: {
      text: data.value.title,
    },
    xAxis: {
      type: 'time',
      splitLine: {
        show: false
      },
      min: beginDate,
      max: endDate,
      boundaryGap: false,
      // x轴模式转换
      axisLabel: {
        formatter: function (value) {
          var date = new Date(value);
          var year = String((date.getFullYear())).substring(2,4); // 年
          var month = String((date.getMonth() + 1)).padStart(2, '0') // 月
          var day = String(date.getDate()).padStart(2, '0'); // 日   
          const hours = String(date.getHours()).padStart(2, '0'); //时
          const minutes = String(date.getMinutes()).padStart(2, '0'); //分
          console.log(mode.value)
          if (mode.value == "year") return year + '-' + month;
          if (mode.value == "month") return month + '-' + day + '\n' + year; // 双行显示，\n 换行
          if (mode.value == "day") return hours;// 双行显示，\n 换行
        }
      }
    },
    yAxis: {
      type: 'value',
      name: data.value.dataUnit,
    },
    legend: {
      // orient: 'vertical',
      // right: -50,
      // icon: 'circle',
      // top: 'center'
      orient: 'horizontal',
      left: 'center',
      top: 'bottom', // 图例垂直居中
      align: 'left',
    },
    series: series.value,
    tooltip: {
      trigger: 'axis',
      confine: true,
      formatter: function (params,) {
        let result=``;
        if(params.length>0&&params[0].value.length>0) result = `<div><strong>${params[0].value[0]}</strong></div>`
        params.forEach(function (item,idx) {
          result += `<div><strong>${item.seriesName} ${Math.floor(item.value[1]*100)/100}${data.value.dataUnit}</strong></div>`;
        });
        return result;
      }
    }
  };
  // 绘制图表
  myChart.setOption(option);
}


onMounted(() => {
  ifPredict.value = props.ifPredict
  data.value = props.data
  if (data.value != null) initChart()
})
</script>

<style lang="scss" scoped>
.main {
  width: 90%;
  height: 90%;
  overflow: hidden;
  display: flex;
  flex: 1;
  box-sizing: border-box;
}
</style>